import React, { Component } from 'react'
import MusicAPI from '@/services/ant-design-pro/music';
import { Modal, Table, Input, message, Space, Button, Spin, Tooltip } from 'antd'
import ComTool from '@/utils/tools'
import './add.less'
const { findMusicByName, updateSongList } = MusicAPI;
class Add extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: [],
            curState: {
                loading: false,
                InputSearchText: undefined,
                selectedRowKeys: [],// 选中的数组内容
            },
        };

        this.InputTimer = null;
        this.LoadingTimer = null;
    }

    setCurState = (action) => {
        const { curState } = this.state;
        this.setState({
            curState: {
                ...curState,
                ...action
            }
        });
    }

    Loading = () => { // 是否加载
        this.LoadingTimer && clearTimeout(this.LoadingTimer);
        this.LoadingTimer = setTimeout(() => {
            this.setCurState({
                loading: false
            })
            clearTimeout(this.LoadingTimer);
        }, 500);
    }

    handleClick = async () => { // 提交
        const { initData, setData, isShowModal } = this.props;
        const { curState, data } = this.state;
        const { selectedRowKeys } = curState;

        let arr = ComTool.uniqueArr([
            ...initData.music_ids,
            ...selectedRowKeys
        ]);

        let result = await updateSongList({
            data: {
                list_id: initData.list_id,
                music_ids: arr.toString(),
                song_nums: arr.length
            }
        })
        if (result.status == 'ok') {
            await setData();
            this.setState({
                data: []
            })
            this.setCurState({
                selectedRowKeys: []
            })
            message.success("修改成功");
        } else {
            message.error('修改失败：' + result.data.message);
            console.log(result.data.error);
        }
        isShowModal('add', false);
    }

    setMusiclistData = async (name) => { // 音乐列表数据设置
        let result = await findMusicByName({
            name
        })

        this.setState({
            data: result.data.value
        })
    }
    handleInputChange = (e) => {  // 搜索框输入内容监听
        this.setCurState({
            loading: true,
        })

        this.InputTimer && clearTimeout(this.InputTimer);
        this.InputTimer = setTimeout(() => {
            this.setMusiclistData(e.target.value);
            this.setCurState({
                InputSearchText: e.target.value || null
            })
            this.Loading();
        }, 500); // 输入完毕后 延迟0.5秒 发送请求
    }


    onSelectChange = selectedRowKeys => { // 选中改变
        this.setCurState({ selectedRowKeys });
    };

    render() {
        const { isModalVisible, isShowModal, initData } = this.props;
        const { curState, data } = this.state;
        const { selectedRowKeys, loading, InputSearchText } = curState;

        const columns = [
            {
                title: '歌曲',
                dataIndex: 'music_name',
                render: (text, record) => {
                    let i = initData.music_ids.indexOf(record.music_id) == '-1';
                    let [a, b] = text.split(InputSearchText);
                    return {
                        children: < Tooltip Tooltip title={i ? "" : "已添加"} >
                            <span>
                                {a}{
                                    text.indexOf(InputSearchText) == '-1' ? "" :
                                        <span style={{ color: 'red' }}>{InputSearchText}</span>
                                }{b}
                            </span>
                        </ Tooltip >
                    }
                }
            },
            {
                title: '歌手',
                dataIndex: 'singer_name', render: (text, record) => {
                    let [a, b] = text.split(InputSearchText);
                    return {
                        children: <span>{a} {
                            text.indexOf(InputSearchText) == '-1' ? "" :
                                <span style={{ color: 'red' }}>{InputSearchText}</span>
                        } {b}</span>

                    }
                }
            },
            {
                title: '专辑',
                dataIndex: 'album_name', render: (text, record) => {
                    let [a, b] = text.split(InputSearchText);
                    return {
                        children: <span>{a}{
                            text.indexOf(InputSearchText) == '-1' ? "" :
                                <span style={{ color: 'red' }}>{InputSearchText}</span>
                        }{b}</span>
                    }
                }
            },
        ];

        return (
            <Modal
                width="600px"
                title={`添加歌曲`}
                footer={false}
                visible={isModalVisible}
                onCancel={() => isShowModal('add', false)}
                destroyOnClose={true}>
                {
                    <div>
                        <Space>
                            <span>搜索：</span>
                            <Input placeholder="歌曲名/歌手/专辑" onChange={e => this.handleInputChange(e)} />
                        </Space>
                        <Spin spinning={loading}>
                            <Table rowSelection={{
                                selectedRowKeys,
                                onChange: this.onSelectChange,
                                onSelectAll: this.onSelectAll,
                                selections: [
                                    {
                                        key: 'All',
                                        text: '选择全部',
                                        onSelect: changableRowKeys => {
                                            let newSelectedRowKeys = [];
                                            data.map((key, index) => {
                                                if (initData.music_ids.toString().indexOf(key.music_id) == '-1' && key.is_lock != '-1') {
                                                    newSelectedRowKeys.push(key.music_id)
                                                }
                                            });
                                            this.setCurState({ selectedRowKeys: newSelectedRowKeys });
                                        },
                                    },
                                    Table.SELECTION_NONE,
                                ],
                                getCheckboxProps: ((record) => {
                                    return {
                                        disabled: initData.music_ids.indexOf(record.music_id) != '-1' || record.is_lock == '-1'
                                    }
                                }),
                            }} rowClassName={(record, index) => {
                                return record.is_lock == '-1' ? 'song_islock' : ''
                            }} columns={columns} dataSource={data} rowKey="music_id" />
                        </Spin>
                        <Button onClick={this.handleClick} disabled={selectedRowKeys.length ? false : true}>提交</Button>
                    </div>
                }
            </Modal>
        );
    }
}

export default Add